/*ui_mask编辑*/
(function ($) {
    $.fn.yqTableEdit = function (opts, param) {
        if (typeof opts == 'string') {
            return $.fn.yqTableEdit.methods[opts](this, param);
        }

        var $this = this;
        var opt = $.extend({}, $.fn.yqTableEdit.defaults, opts);
        if ($this.data("yqtype") == "yqTableEdit") {
            var $uniqueID = $this.attr("ID");
            destroy($this);
            $this = $("#" + $uniqueID);
        }
        else {
            var $uniqueID = $this.attr("ID");
            if ($uniqueID === undefined) {
                $uniqueID = $.getUniqueID();
                $this.attr("ID", $uniqueID);
            }
        }

        if (opt.editModeW === undefined && $this.width() > 0) {
            opt.editModeW = $this.width();
        }
        else {
            if (opt.editModeW === undefined) {
                opt.editModeW = 400;
            }
            $this.width(opt.editModeW);
        }

        if (opt.editModeH === undefined && $this.height() > 0) {
            opt.editModeH = $this.height();
        }
        else {
            if (opt.editModeH === undefined) {
                opt.editModeH = 300;
            }
            $this.height(opt.editModeH);
        }

        opt.on_load = false;
        opt._isMove = false;

        opt.fk_rows = [];

        if (opt.checkBoxCol) {
            opt.frozenNum = opt.frozenNum + 1;
        }

        //变量信息
        $this.data("tableedit_opt", opt);
        $this.data("yqtype", "yqTableEdit");
        init_pg_before($this);
    };

    $.fn.yqTableEdit.defaults = {
        ajaxUrl: "/_db.html",
        titles: [],  //数据列配置对象
        rows: [],
        // editModeW: 500,      //模态编辑器宽度 格式为 800（数字）
        // editModeH: 300,      //模态编辑器高度 格式为 600（数字）
        editType: 0,            //编辑模式 0:行编辑模式 1:属性编辑模式 2:form编辑模式
        modelNo: -1,            //当前模型编号
        panelWidth: 500,        //面板宽度 editType=1\2 时生效
        panelHeight: 400,       //面板高度 editType=1\2 时生效
        isEdit: true,
        isAdd: true,
        isDel: true,
        isMove: true,
        toexcel: false, //Excel导出
        excelName: "excel导出",   //Excel导出文件名
        inexcel: false, //Excel导入
        frozenNum: 0, //锁定列数量（锁定左侧）
        rownumbers: true,
        sumList: [],        //合计字段：a,b,c
        showHeader: true,        //是否显示表头
        beforBindingTitle: function (titles, callback) {
            callback(titles);
        }, //标题绑定前
        afterBindingTitle: function () { },   //标题绑定后
        beforeSetFooter: function (rows, footer) {
            return footer;
        },
        onLoadSuccess: function (datagrid, data) { },
        onClickRow: function (index, row) { },
        beginEdit: function (index, row) {

        },
        endEditing: function (index, row) {   //ok.....
        },
        beforeAdd: function (rows, row, callback) { //ok....
            callback(row);
        },
        beforeDel: function (row, callback) { //ok....
            callback(true);
        },

        beforeToExcel: function (title, rows, mergeCells, callback) { //Excel导出前数据处理
            callback(title, rows, mergeCells);
        },

        checkBoxCol: false,   //行选择复选框
        checkBoxFormatter: function (value, row, index) {  //选择渲染事件,true 渲染
            return true;
        },
        checkBoxChecked: function (checkCount) {  //行选择事件 选择的数量
            // console.log("checkCount", checkCount);
        },
        checkBoxChange: function (row, checked) {
            // console.log("checkBoxChange", row, checked);
        },   //选择事件 行，是否选中
    };

    $.fn.yqTableEdit.methods = {
        options: function (jq) {
            return options(jq);
        },
        setTitles: function (jq, titles) {
            var opt = options(jq)
            opt.titles = $.yqFmUiTitle(titles);
            opt.beforBindingTitle.call(jq, opt.titles,
                function (titles) {
                    opt.titles = titles;
                });
        },
        setRows: function (jq, rows) {   //[{"ui_type":2,"value":""}]
            setRows(jq, rows);
        },
        reLoad: function (jq) {
            reLoad(jq);
        },
        clear: function (jq) {
            setRows(jq, []);
        },
        getRows: function (jq) {  //获取后编辑状态改变
            return getRows(jq, false);
        },
        getRows_2: function (jq) {   //获取后编辑状态不改变
            return getRows(jq, true);
        },
        getSelected: function (jq) {
            if (endEditing(jq)) {
                return jq.datagrid("getSelected");
            } else {
                return null;
            }
        },
        getSelectedIndex: function (jq) {
            if (endEditing(jq)) {
                var row = jq.datagrid("getSelected");
                return jq.datagrid("getRowIndex", row);
            } else {
                return -1;
            }
        },
        updateRow: function (jq, params) {
            jq.datagrid('updateRow', {
                index: params.index,
                row: params.row
            });
            if (params.isEdit) {
                jq.datagrid('beginEdit', params.index);
                jq.datagrid("options").editIndex = params.index;
            }
        },
        isEdit: function (jq, tf) {
            isEdit(jq, tf);
        },
        destroy: function (jq) {
            destroy($(jq[0]));
        },
        resize: function (jq, params) {
            resize($(jq[0]), params)
        },
        setField: function (jq, para) {
            if (para === undefined) {
                return;
            }
            if (para.name === undefined) {
                return;
            }
            if (para.value === undefined) {
                return;
            }

            setfield(jq, para.name, para.value)
        },
        getField: function (jq, name) {
            if (name === undefined) {
                return null;
            }

            return getfield(jq, name);
        },
        getFieldObj: function (jq, name) {
            if (name === undefined) {
                return null;
            }

            return getfieldObj(jq, name);
        },
        endEditing: function (jq) {
            endEditing(jq);
            jq.datagrid("unselectAll");
        },

        checkAll: function (jq, checked) { //全部选择、不选择
            var opt = options(jq);
            var $yq_checkbox = jq.closest('div.datagrid-view').find(".yq_checkbox");
            $yq_checkbox.prop("checked", checked);
            var checkCount = $yq_checkbox.filter(":checked").length;
            opt.checkBoxChecked.call(jq, checkCount);

            var rows = jq.datagrid("getRows");
            for (var i = 0; i < $yq_checkbox.length; i++) {
                var index = parseInt($($yq_checkbox[i]).attr("tag"));
                opt.checkBoxChange.call(jq, rows[index], $yq_checkbox[i].checked);
            }
        },
        checkBoxRows: function (jq) {   //取得多选行的数据
            var $yq_checkbox = jq.closest('div.datagrid-view').find(".yq_checkbox");
            var rows = jq.datagrid("getRows");
            var _rows = [];
            for (var i = 0; i < $yq_checkbox.length; i++) {
                var index = parseInt($($yq_checkbox[i]).attr("tag"));
                if ($yq_checkbox[i].checked) {
                    _rows.push($.extend({}, rows[index]));
                }
            }
            return _rows;
        },
        setCheckBoxRow: function (jq, param) { //设置checkbox按钮是否选中
            var $yq_checkbox = jq.closest('div.datagrid-view').find(".yq_checkbox");
            for (var i = 0; i < $yq_checkbox.length; i++) {
                var $ck = $($yq_checkbox[i]);
                var index = parseInt($ck.attr("tag"));
                if (index == param.index) {
                    $ck.prop("checked", param.checked);
                    $ck.trigger('change');
                    break;
                }
            }
        },
    };

    function options($object) {
        return $object.data("tableedit_opt");
    }

    function destroy($object) {
        var opt = options($object);
        var $uniqueID = $object.attr("id");
        if (typeof opt.$menu != "undefined") {
            opt.$menu.menu("destroy");
        }
        if (typeof opt.$toolbar != "undefined") {
            opt.$toolbar.remove();
        }

        var $div = $object.closest("div.datagrid");
        $div.before($object);
        $object.show();
        $div.remove();

        $object.removeClass("datagrid-f");
        $object.css({ width: opt.editModeW, height: opt.editModeH });

        $object.removeData("tableedit_opt");
        $object.removeData("yqtype");

        var $table = $("<table></table>");
        $table.css({ width: opt.editModeW, height: opt.editModeH });
        $object.before($table);
        $object.remove();
        $table.attr("id", $uniqueID);
    }

    function resize($object, params) {
        var opt = options($object);
        if (!(params === undefined)) {
            if (!(params.width === undefined)) {
                opt.width = params.width;
            }
            if (!(params.height === undefined)) {
                opt.height = params.height;
            }
        }

        $object.datagrid("resize", {
            width: opt.width,
            height: opt.height
        });
    }

    function isEdit($object, tf) {
        var opt = options($object);
        opt.isEdit = tf;
        if (endEditing($object)) {
            opt.rows = getRows($object);
            reLoad($object);
        }
    }

    function init_pg_before($object) {
        var opt = options($object);
        opt.titles = $.yqFmUiTitle(opt.titles);
        opt.beforBindingTitle.call($object, opt.titles,
            function (titles) {
                opt.titles = titles;
                //if (opt.editType == 0) {
                init_pg($object);
                //} else if (opt.editType == 1) {
                //    init_pg_attr($object);
                //} else if (opt.editType == 2) {
                //    init_pg_form($object);
                //}
            });
    }

    function init_pg($object) {
        var opt = options($object);
        var $uniqueID = $object.attr("id");

        opt.$toolbar = $("<div></div>");
        if (opt.isAdd) {
            opt.$toolbar.append('<a id="' + "toolbar_" + $uniqueID + "_add" + '"></a>');
            opt.$toolbar.append('<a id="' + "toolbar_" + $uniqueID + "_copy" + '"></a>');
            if (opt.isDel) {
                opt.$toolbar.append('<a class="pagination-btn-separator" style="float: none;" href="javascript:void(0);"></a>');
            }
        }

        if (opt.isDel) {
            opt.$toolbar.append('<a id="' + "toolbar_" + $uniqueID + "_del" + '"></a>');
        }

        if (opt.$toolbar.children().length > 0) {
            var menustr = "";
            if (opt.isAdd) {
                menustr += '<div data-options="name:\'add\',iconCls:\'yqwin-btn-icon-sub fa fa-plus-square\'">添加</div>';
                menustr += '<div data-options="name:\'copy\',iconCls:\'yqwin-btn-icon-sub fa fa-files-o\'">拷贝</div>';
                if (opt.isDel) {
                    menustr += '<div class="menu-sep"></div>';
                }
            }
            if (opt.isDel) {
                menustr += '<div id="menu_' + $uniqueID + '_del", data-options="name:\'del\',iconCls:\'yqwin-btn-icon-sub fa fa-trash\'">删除</div>';
            }

            opt.$menu = $('<div style="width:120px;">' + menustr + '</div>');
            opt.$menu.menu({
                onClick: function (item) {
                    var s_row = $object.datagrid("getSelected");
                    if (item.name == "add") {
                        append($object);
                    } else if (item.name == "copy") {
                        copy($object);
                    }
                    else if (item.name == "del") {
                        removeit($object);
                    }
                }
            });
        }

        var dg_opt = {
            width: opt.editModeW,  //模态编辑器宽度 格式为 800（数字）
            height: opt.editModeH, //模态编辑器高度 格式为 600（数字）
            //columns: $.yqDgColumns.call($object, opt.titles, opt.isEdit),
            //data: { "rows": $.yqFmToViews(opt.rows, opt.titles) },
            columns: [],
            data: { "rows": [] },
            onClickCell: onClickCell,
            beginEdit: function (index) {
                var rows = $(this).datagrid("getRows");
                opt.beginEdit.call($object, index, rows[index])
            },
            onEndEdit: function (index, row) {
                opt.endEditing.call($object, index, row);
                if (opt.sumList.length > 0 && opt.showFooter) {
                    resetFooter($object);
                }
            },
            onClickRow: function (index, row) {
                if (opt.isEdit) {
                    if (opt.isAdd) {
                        $("#toolbar_" + $uniqueID + "_add").linkbutton("enable");
                        if (row == null) {
                            $("#toolbar_" + $uniqueID + "_copy").linkbutton("disable");
                            opt.$menu.menu("disableItem", $("#menu_" + $uniqueID + "_copy"));
                        }
                        else {
                            $("#toolbar_" + $uniqueID + "_copy").linkbutton("enable");
                            opt.$menu.menu("enableItem", $("#menu_" + $uniqueID + "_copy"));
                        }
                    }
                    if (opt.isDel) {
                        if (row == null) {
                            $("#toolbar_" + $uniqueID + "_del").linkbutton("disable");
                            opt.$menu.menu("disableItem", $("#menu_" + $uniqueID + "_del"));
                        }
                        else {
                            $("#toolbar_" + $uniqueID + "_del").linkbutton("enable");
                            opt.$menu.menu("enableItem", $("#menu_" + $uniqueID + "_del"));
                        }
                    }
                    if (opt.inexcel) {
                        $("#toolbar_" + $uniqueID + "_inexcel").linkbutton("enable");
                    }
                }
                else {
                    if (opt.isAdd) {
                        $("#toolbar_" + $uniqueID + "_add").linkbutton("disable");
                        $("#toolbar_" + $uniqueID + "_copy").linkbutton("disable");
                    }
                    if (opt.isDel) {
                        $("#toolbar_" + $uniqueID + "_del").linkbutton("disable");
                    }
                    if (opt.inexcel) {
                        $("#toolbar_" + $uniqueID + "_inexcel").linkbutton("disable");
                    }
                }

                opt.onClickRow.call($object, index, row);
            },

            rownumbers: opt.rownumbers,
            fitColumns: false,

            scrollbarSize: 0,
            singleSelect: true,
            dragSelection: true,
            showHeader: opt.showHeader,
            onRowContextMenu: function (e, index, row) {
                if (opt._isMove || (!opt.isEdit) || (!opt.isAdd) || (!opt.isDel)) {
                    return;
                }
                var row2 = $(this).datagrid("getSelected");
                if (opt.isAdd) {
                    if (row2 == null) {
                        opt.$menu.menu("disableItem", $("#menu_" + $uniqueID + "_copy"));
                    }
                    else {
                        opt.$menu.menu("enableItem", $("#menu_" + $uniqueID + "_copy"));
                    }
                }
                if (opt.isDel) {
                    if (row2 == null) {
                        opt.$menu.menu("disableItem", $("#menu_" + $uniqueID + "_del"));
                    }
                    else {
                        opt.$menu.menu("enableItem", $("#menu_" + $uniqueID + "_del"));
                    }
                }

                if (opt.$toolbar.children().length > 0) {
                    e.preventDefault();
                    opt.$menu.menu('show', {
                        left: e.pageX,
                        top: e.pageY
                    });
                }
            }
        };
        if (opt.checkBoxCol) {
            dg_opt.checkOnSelect = false;
            dg_opt.selectOnCheck = false;
        };

        if (opt.isMove) {
            opt.$toolbar.append('<span id="toolbar_' + $uniqueID + '_move_div"><a id="' + "toolbar_" + $uniqueID + "_move" + '"></a></span>');
        }
        if (opt.toexcel) {
            opt.$toolbar.append('<a id="' + "toolbar_" + $uniqueID + "_toexcel" + '"></a>');
        }
        if (opt.isAdd && opt.inexcel) {
            opt.$toolbar.append('<a id="' + "toolbar_" + $uniqueID + "_inexcel" + '"></a>');
        }

        if (opt.isAdd || opt.isDel || opt.isMove || opt.toexcel || opt.inexcel) {
            $object.append(opt.$toolbar);
            dg_opt.toolbar = opt.$toolbar;
        }

        if (opt.isAdd) {
            $("#toolbar_" + $uniqueID + "_add").linkbutton({
                text: '添加',
                iconCls: 'yqwin-btn-icon fa fa-plus-square',
                plain: true,
                onClick: function () {
                    append($object);
                }
            });

            $("#toolbar_" + $uniqueID + "_copy").linkbutton({
                text: '拷贝',
                iconCls: 'yqwin-btn-icon fa fa-files-o',
                plain: true,
                onClick: function () {
                    copy($object);
                }
            });
        }
        if (opt.isDel) {
            $("#toolbar_" + $uniqueID + "_del").linkbutton({
                text: '删除',
                iconCls: 'yqwin-btn-icon fa fa-trash',
                plain: true,
                onClick: function () {
                    removeit($object);
                }
            });
        }

        if (opt.toexcel) {
            $("#toolbar_" + $uniqueID + "_toexcel").linkbutton({
                text: 'Excel导出',
                iconCls: 'yqwin-btn-icon-sub fa fa-file-excel-o',
                plain: true,
                onClick: function () {
                    btn_toexcel($object);
                }
            });
        }
        if (opt.inexcel) {
            $("#toolbar_" + $uniqueID + "_inexcel").linkbutton({
                text: 'Excel导入',
                iconCls: "yqwin-btn-icon-sub fa fa-table",
                plain: true,
                onClick: function () {
                    btn_inexcel($object);
                }
            });
        }

        if (opt.isMove) {
            $("#toolbar_" + $uniqueID + "_move").data("p_object", $object)
            $("#toolbar_" + $uniqueID + "_move").switchbutton({
                width: 55,
                height: 23,
                checked: false,
                handleText: '<span class="yqwin-btn-icon fa fa-sort" aria-hidden="true"></span>',
                onText: "on",
                offText: "off",
                onChange: function (checked) {
                    opt._isMove = checked;
                    if (checked) {
                        if (endEditing($object)) {
                            $object.datagrid('enableDnd');
                            if (opt.isAdd) {
                                $("#toolbar_" + $uniqueID + "_add").linkbutton("disable");
                                $("#toolbar_" + $uniqueID + "_copy").linkbutton("disable");
                            }
                            if (opt.isDel) {
                                $("#toolbar_" + $uniqueID + "_del").linkbutton("disable");
                            }
                            if (opt.isAdd && opt.inexcel) {
                                $("#toolbar_" + $uniqueID + "_inexcel").linkbutton("disable");
                            }
                        }
                    } else {
                        $object.datagrid('disableDnd');
                        if (opt.isAdd) {
                            $("#toolbar_" + $uniqueID + "_add").linkbutton("enable");
                            $("#toolbar_" + $uniqueID + "_copy").linkbutton("enable");
                        }
                        if (opt.isDel) {
                            $("#toolbar_" + $uniqueID + "_del").linkbutton("enable");
                        }
                        if (opt.isAdd && opt.inexcel) {
                            $("#toolbar_" + $uniqueID + "_inexcel").linkbutton("enable");
                        }
                    }
                }
            });
        }

        if (opt.sumList.length > 0) {
            var hasFooter = false;
            for (var i = 0; i < opt.sumList.length; i++) {
                var name = opt.sumList[i];
                for (var j = 0; j < opt.titles.length; j++) {
                    if (opt.titles[j].name == name && opt.titles[j].ui_visible) {
                        hasFooter = true;
                        break;
                    }
                }
                if (hasFooter) {
                    break;
                }
            }

            opt.showFooter = hasFooter;
            dg_opt.showFooter = hasFooter;

            if (hasFooter) {
                dg_opt.data = setFooter($object, dg_opt.data);
            }
        }

        dg_opt = setFrozen(opt, dg_opt);
        $object.datagrid(dg_opt);

        if (opt.isMove) {
            $("#toolbar_" + $uniqueID + "_move_div").find('span.switchbutton').css({
                "margin": "4px"
            });
        }

        reLoad($object);
    }

    function reLoad($object) {
        var opt = options($object);
        var $uniqueID = $object.attr("id");
        var columns = $.yqDgColumns.call($object, opt.titles, opt.isEdit);

        if (opt.checkBoxCol) {
            columns[0].unshift({
                title: '<input type="checkbox" onchange="$(\'#' + $object.attr("id") + '\').yqTableEdit(\'checkAll\',this.checked)"></input>',
                field: '_my_checkbox',
                width: 30,
                formatter: function (value, row, index) {
                    if (row["_footer_"] === undefined && opt.checkBoxFormatter.call($object, value, row, index)) {
                        var $yq_checkbox = $object.closest('div.datagrid-view').find(".yq_checkbox");
                        if ($yq_checkbox.length > 0 && $yq_checkbox.length >= index) {
                            if ($yq_checkbox[index].checked) {
                                return '<input class="yq_checkbox" type="checkbox" tag="' + index + '" checked></input>';
                            }
                        }
                        return '<input class="yq_checkbox" type="checkbox" tag="' + index + '"></input>';
                    } else {
                        return '';
                    }
                }
            });
        }

        setForienKeys($object, opt.rows,
            function () {
                var data = { "rows": $.yqFmToViews(opt.rows, opt.titles) };
                if (opt.sumList.length > 0 && opt.showFooter) {
                    data = setFooter($object, data);
                }

                var dg_opt = {
                    columns: columns,
                    data: data,
                    onLoadSuccess: function () {
                        var opt_dg = $(this).datagrid('options');
                        opt_dg.onLoadSuccess = function () { };

                        if (opt.isDel) {
                            opt.$menu.menu("disableItem", $("#menu_" + $uniqueID + "_del"));
                        }
                        if (opt.isEdit) {
                            if (opt.isAdd) {
                                $("#toolbar_" + $uniqueID + "_add").linkbutton("enable");
                                $("#toolbar_" + $uniqueID + "_copy").linkbutton("disable");
                            }
                            if (opt.isDel) {
                                $("#toolbar_" + $uniqueID + "_del").linkbutton("disable");
                            }

                            $("#toolbar_" + $uniqueID + "_move").switchbutton("enable");
                        }
                        else {
                            $("#toolbar_" + $uniqueID + "_add").linkbutton("disable");
                            $("#toolbar_" + $uniqueID + "_copy").linkbutton("disable");
                            $("#toolbar_" + $uniqueID + "_del").linkbutton("disable");

                            $("#toolbar_" + $uniqueID + "_move").switchbutton("disable");
                        }

                        if (!opt.isEdit) {
                            $object.datagrid('disableDnd');
                        }

                        if (!opt.on_load) {
                            opt.on_load = true;
                            opt.afterBindingTitle.call($object);
                        }

                        opt.onLoadSuccess.call($object, this, data);

                        if (opt.checkBoxCol) {
                            var $yq_checkbox = $object.closest('div.datagrid-view').find(".yq_checkbox");
                            $yq_checkbox.unbind();
                            $yq_checkbox.bind("change", function () {
                                var checkCount = $yq_checkbox.filter(":checked").length;
                                opt.checkBoxChecked.call($object, checkCount);

                                var rows = $object.datagrid("getRows");
                                var index = parseInt($(this).attr("tag"));
                                opt.checkBoxChange.call($object, rows[index], this.checked);
                            });
                        }
                    },
                };

                dg_opt = setFrozen(opt, dg_opt);
                $object.datagrid(dg_opt);
            });
    }

    function setFrozen(opt, dg_opt) {
        if (opt.frozenNum > 0 && dg_opt.columns.length > 0
            && opt.frozenNum < dg_opt.columns[0].length) {
            var columns_0 = $.extend([], dg_opt.columns[0]);
            var f_columns = [];
            for (var i = 0; i < opt.frozenNum; i++) {
                f_columns.push($.extend({}, columns_0[i]));
            }
            columns_0.splice(0, opt.frozenNum);
            if (dg_opt.columns.length == 1) {
                dg_opt.columns = [columns_0];
            }
            else {
                dg_opt.columns = [columns_0, dg_opt.columns[1]];
            }

            dg_opt.frozenColumns = [f_columns];
        }
        return dg_opt;
    }

    function setFooter($object, data) {
        var footer = getFooter($object, data.rows);
        data.footer = footer;

        return data;
    }

    function resetFooter($object) {
        var opt = options($object);
        var rows = $object.datagrid("getRows");
        var footer = getFooter($object, rows);

        $object.datagrid('reloadFooter', footer);
    }

    function getFooter($object, rows) {
        var opt = options($object);

        var footer = {
            "_footer_": true
        };
        for (var j = 0; j < opt.sumList.length; j++) {
            footer[opt.sumList[j]] = 0;
        }
        for (var i = 0; i < rows.length; i++) {
            for (var j = 0; j < opt.sumList.length; j++) {
                var name = opt.sumList[j];
                var num = rows[i][name];
                try {
                    num = ((num === undefined || num === null) ? 0 : parseFloat(num));
                    if (isNaN(num)) {
                        num = 0;
                    }
                } catch (err) {
                    num = 0;
                }
                footer[name] += num;
            }
        }

        return opt.beforeSetFooter.call($object, rows, [footer]);
    }

    function endEditing($object) {
        var _opt = $object.datagrid("options");
        if (_opt.editIndex == undefined) { return true }
        if ($object.datagrid('validateRow', _opt.editIndex)) {
            $object.datagrid('endEdit', _opt.editIndex);
            _opt.editIndex = undefined;
            return true;
        } else {
            return false;
        }
    }

    function onClickCell(index, field) {
        var $object = $(this);
        var opt = options($object);

        if (opt._isMove || (!opt.isEdit)) {
            return;
        }

        var $uniqueID = $object.attr("ID")
        var _opt = $object.datagrid("options");

        if (_opt.editIndex == index) {
            return;
        }

        if (endEditing($object)) {
            delete _opt.editIndex;
            $object.datagrid('selectRow', index)
                .datagrid('beginEdit', index);
            var ed = $object.datagrid('getEditor', { index: index, field: field });
            if (ed) {
                ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
            }
            _opt.editIndex = index;

            opt.beginEdit.call($object, index, opt.rows[index]);
        }
    }

    function append($object, row) {
        var opt = options($object);

        var _opt = $object.datagrid("options");
        if (endEditing($object)) {
            var rows = $object.datagrid("getRows");
            if (row === undefined) {
                row = {};
            }

            opt.beforeAdd.call($object, rows, row,
                function (row2) {
                    $object.datagrid('appendRow', row2);
                    _opt.editIndex = $object.datagrid('getRows').length - 1;
                    $object.datagrid('selectRow', _opt.editIndex)
                        .datagrid('beginEdit', _opt.editIndex);
                });
        }
    }

    function copy($object) {
        var row = $object.datagrid("getSelected");
        if (row === null) {
            return;
        }

        append($object, $.extend({}, row));
    }

    function removeit($object) {
        var opt = options($object);
        var row = $object.datagrid("getSelected");
        if (row === null) {
            return;
        }
        opt.beforeDel.call($object, row,
            function (tf) {
                if (tf) {
                    var _opt = $object.datagrid("options");
                    if (_opt.editIndex == undefined) {
                        return;
                    }
                    $object.datagrid('cancelEdit', _opt.editIndex)
                        .datagrid('deleteRow', _opt.editIndex);

                    _opt.editIndex = undefined;
                }
            });
    }

    function setRows($object, rows) {
        var opt = options($object);
        if (rows === undefined || rows == null || rows == "") {
            rows = [];
        }
        if (typeof rows === "string") {
            rows = JSON.parse(rows);
        }
        opt.rows = rows;
        reLoad($object);
    }

    function getfieldObj($object, field) {
        var opt = options($object);

        var index = $object.datagrid("options").editIndex;
        if (index === undefined) {
            return;
        }

        var $editor = $object.datagrid("getEditor", {
            index: index,
            field: field
        });

        if ($editor === null) {
            return null;
        }

        return $editor.target;
    }

    function getfield($object, field) {
        var opt = options($object);

        var index = $object.datagrid("options").editIndex;
        if (index === undefined) {
            return;
        }

        var $editor = $object.datagrid("getEditor", {
            index: index,
            field: field
        });

        if ($editor === null) {
            return $object.datagrid("options").data.rows[index][field];
        } else {
            return $.yqDgEditorGetValue($editor.target)
        }
    }

    function setfield($object, field, val) {
        var opt = options($object);

        var index = $object.datagrid("options").editIndex;
        if (index === undefined) {
            return;
        }

        if (val === undefined) {
            val = null;
        }

        if (index < opt.rows.length) {
            if (val === null) {
                delete opt.rows[index][field];
            } else {
                opt.rows[index][field] = val;
            }
        }

        var $editor = $object.datagrid("getEditor",
            {
                index: index,
                field: field
            });

        if ($editor === null) {
            var row = $object.datagrid("options").data.rows[index];
            if (val === null) {
                delete row[field];
            } else {
                row[field] = val;
            }
            var $td = $object.closest('div.datagrid-view')
                .find(".datagrid-view2")
                .find('tr[datagrid-row-index="' + index + '"]')
                .find('td[field="' + field + '"]');
            if ($td.length > 0) {
                $td.find('div').html(val);
                $object.datagrid("options").data.rows[index][field] = val;
            }
        } else {
            $.yqDgEditorSetValue($editor.target, val)
        }
    }

    //外键处理
    function setForienKeys($object, rows, callback) {
        var opt = options($object);
        var opts = {
            "ajaxUrl": opt.ajaxUrl,
            "rows": rows,
            "titles": opt.titles,
            "fk_rows": opt.fk_rows
        };

        if (typeof opt._appno != undefined) {
            opts.ctrlid = opt._ctrlid;
            opts.appno = opt._appno;
            opts.menuno = opt._menuno;
        }

        $.yqGetForeignkeys(opts,
            function (fk_rows) {
                opt.fk_rows = fk_rows;
                callback();
            });
    }

    function getRows($object, edit) {
        if (edit === undefined) {
            edit = false;
        }
        var opt = options($object);
        var opt_ = $object.datagrid("options");
        var editIndex = opt_.editIndex;
        if (endEditing($object)) {
            var rows = $object.datagrid("getRows");
            if (rows.length == 0) {
                rows = [];
            }
            else {
                rows = $.yqFmToDatas(rows, opt.titles, opt.fk_rows);
            }
            opt.rows = rows;

            if (edit && !(editIndex === undefined)) {
                $object.datagrid('selectRow', editIndex)
                    .datagrid('beginEdit', editIndex);
                opt_.editIndex = editIndex;
            }

            return rows;
        }
        else {
            return opt.rows;
        }
    }

    function btn_toexcel($object) {
        var opt = options($object);
        var rows = [];

        var f_rows = $object.datagrid("getRows");

        for (let i = 0; i < f_rows.length; i++) {
            var row = $.extend({}, f_rows[i]);
            for (var j = 0; j < opt.titles.length; j++) {
                var para = $.extend({}, opt.titles[j]);
                para.value = row[opt.titles[j].name];
                if (para.ui_type == 3) { //checkbox
                    row[opt.titles[j].name] = para.value;
                } else if (para.ui_type == 6 ||
                    para.ui_type == 7 ||
                    para.ui_type == 8 ||
                    para.ui_type == 13 ||
                    para.ui_type == 14
                ) {
                    row[opt.titles[j].name] = para.value;
                    row[opt.titles[j].name + "_val"] = $.yqPgFormatter.call({ p_target: $object }, para);
                } else {
                    row[opt.titles[j].name] = $.yqPgFormatter.call({ p_target: $object }, para);
                }
            }
            rows.push(row);
        }

        var row_title = [];
        for (var i = 0; i < opt.titles.length; i++) {
            var para = opt.titles[i];
            row_title.push({
                name: para.name,
                title: para.ui_title,
                width: para.ui_width
            });
            if (para.ui_type == 6 ||
                para.ui_type == 7 ||
                para.ui_type == 8 ||
                para.ui_type == 13 ||
                para.ui_type == 14
            ) {
                row_title.push({
                    name: para.name + "_val",
                    title: para.ui_title + "_val",
                    width: para.ui_width
                });
            }
        }

        //console.log(row_title, rows);  
        var mergeCells = [];
        opt.beforeToExcel.call($object, row_title, rows, mergeCells,
            function (row_title_, rows_, mergeCells_) {
                $.yqDataToExcel({
                    filename: opt.excelName + ".xls",
                    header: row_title_,
                    data: rows_,
                    mergeCells: mergeCells_,
                }, function (res) {
                    //console.log(res);
                });
            });
    }

    function btn_inexcel($object) {
        console.log("todo inexcel");
    }
})(jQuery);

